package it.polimi.swKnights.SWIMv2.utility;

import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidDateException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DateUtility
{
	/**
	 * Class used to parse string Date field to java.util.Date
	 * 
	 * @param stringDate
	 *            the string to be parsed
	 * @return the Date reppresenting the string or now, if the string is
	 *         invalid
	 */
	public static Date getDate(String stringDate)
	{
		Date date;
		try
		{

			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
					Locale.ENGLISH);
			date = formatter.parse(stringDate);

		}
		catch (ParseException pe)
		{
			System.err.println("errore compleanno");
			date = new Date();
		}
		return date;
	}

	/**
	 * returns a classical date representation: dd/mm/yyyy
	 * 
	 * @param date
	 * @return string
	 */
	public static String getStringDate(Date date)
	{
		SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");

		return df.format(date);

	}

	/**
	 * throws an exception if the date is inthe past
	 * 
	 * @param date
	 *            the date to be checked
	 * @throws InvalidDateException
	 */
	public static void checkAfterToday(Date date) throws InvalidDateException
	{	

		Date today = new Date();
		
		if(date.before(today))
		{
			throw new InvalidDateException();
		}

	}

	public static boolean checkBetween(Date date, int nDays)
	{
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DAY_OF_YEAR, nDays);
		
		Date afterNDays = cal.getTime();
		
		Date today = new Date();
		
		return today.after(date) && today.before(afterNDays);
	}
}
